
class Sheet < ActiveRecord::Base
	require 'roo'
	# require "spreadsheet"
 #  	Spreadsheet.client_encoding = "UTF-8" 

	mount_uploader :file, SheetUploader

	belongs_to :creator, :class_name => 'User'


	def open_excel_file
		filename = self.file.path
	    ex = case filename[/\.[^\.]+$/]
	    when ".xlsx" then  Roo::Excelx.new(filename) 
	    when ".xls" then Roo::Excel.new(filename) 
	    end
	    ex.default_sheet = ex.sheets.first
	    return ex
  	end

	def import
		excel = self.open_excel_file()
    	return false if excel.nil?
    	2.upto excel.last_row do |i|
    	 	row	 = excel.row(i)
    	 	name = row[0]
      		email = row[1]
      		#phone = row[2]

      		user = User.find_by_email(email)
      		unless user
      			user  = User.new(:name=>name,:email=>email,:password => '12345678', :password_confirmation => '12345678',:enabled=>true)
      		end
      		user.phone = row[2].to_i unless row[2].blank?
      		self.users_count += 1 if user.valid? && user.save
    	end
 		self.imported=true
      	self.save

	end


end
